<template>
  <div class="goodsConfig h100" v-loading="loading">
    <div class="pageContent">
      <el-form
        class="form"
        :model="ruleForm"
        :inline="true"
        ref="ruleForm"
        label-width="80px"
      >
        <el-row :gutter="11" class="fileSearch">
          <el-form-item label="商品名称:" prop="title">
            <el-input v-model="ruleForm.title" clearable></el-input>
          </el-form-item>
          <el-form-item label="商品类型:" prop="categoryId">
            <el-select v-model="ruleForm.categoryId" placeholder="请选择类型">
              <!-- @change="setTypeShow" -->
              <el-option label="全部" value=""></el-option>
              <el-option
                v-for="item in goodsTypeList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item v-if="typeShow" label="是否收费:" prop="categoryId">
            <el-select v-model="ruleForm.category" placeholder="请选择类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="收费" :value="0"></el-option>
              <el-option label="不收费" :value="1"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="onSubmit(1)">
              查询
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            <el-button icon="el-icon-plus" type="success" @click="dialogVisible = true"
              >新增</el-button
            >
          </el-form-item>
        </el-row>
        <div class="table_wrapper">
          <el-table
            :data="tableData"
            border
            :header-cell-style="{
              background: 'rgb(246,247,251)',
              color: '#606266',
            }"
            stripe
            class="defaultTableHeight"
          >
            <el-table-column type="index" label="编号" width="50"> </el-table-column>
            <el-table-column prop="title" align="center" label="商品名称">
            </el-table-column>
            <el-table-column prop="originalPrice" align="center" label="免费价格">
              <template slot-scope="scope">
                {{ scope.row.originalPrice
                }}{{ scope.row.bigCategoryCode == "sweep" ? "元" : "祭祀币" }}
              </template>
            </el-table-column>
            <el-table-column prop="price" align="center" label="收费价格">
              <template slot-scope="scope">
                {{ scope.row.price
                }}{{ scope.row.bigCategoryCode == "sweep" ? "元" : "祭祀币" }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="vipPrice" align="center" label="vip价格">
          </el-table-column> -->
            <!-- <el-table-column prop="sales" align="center" label="库存">
          </el-table-column> -->
            <el-table-column prop="validTime" align="center" label="有效天数">
            </el-table-column>
            <!-- <el-table-column prop="specificType" align="center" label="商品类型">
            <template slot-scope="scope">
              {{ scope.row.specificType | specificTypeChange }}
              <el-option label="代祭扫商品" value="sweep"></el-option>
            <el-option label="供奉商品" value="article"></el-option>
            <el-option label="祭祀的长明灯" value="lantern"></el-option>
            </template>
          </el-table-column> -->
            <el-table-column prop="categoryTitle" align="center" label="商品类型">
              <!-- <template slot-scope="scope">
              {{ scope.row.category }}
            </template> -->
            </el-table-column>
            <el-table-column align="center" label="图片">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.imgUrl1"
                  :src="scope.row.imgUrl1"
                  alt=""
                  :preview-src-list="[scope.row.imgUrl1]"
                ></el-image>
                <!-- <video
                v-if="scope.row.spuType == 'mp3'"
                :src="scope.row.imgUrl"
              ></video> -->
                <el-image
                  v-if="scope.row.imgUrl2"
                  :src="scope.row.imgUrl2"
                  alt=""
                  :preview-src-list="[scope.row.img2Url2]"
                ></el-image>
                <!-- <video
                v-if="scope.row.spuType == 'mp3'"
                :src="scope.row.img2Url"
              ></video> -->
              </template>
            </el-table-column>

            <el-table-column prop="description" align="center" label="商品描述">
              <!-- <template slot-scope="scope">
              {{ scope.row.category }}
            </template> -->
            </el-table-column>
            <!-- <el-table-column align="center" label="商家状态">
            <template slot-scope="scope">
             

              <el-tag v-if="scope.row.state === 1" type="success">上架</el-tag>
              <el-tag v-if="scope.row.state === 0" type="info">下架</el-tag>
            </template>
          </el-table-column> -->
            <el-table-column label="操作" align="center" width="200px">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="updataGoods(scope.row.id)"
                  >编辑</el-button
                >
                <el-button type="danger" size="mini" @click="delGoods(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <p style="text-align: right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pager.currentPage"
              :page-size="pager.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              background
              layout="total,sizes,prev, pager, next, jumper"
              :total="pager.total"
            >
            </el-pagination>
          </p>
        </div>
      </el-form>
    </div>
    <el-dialog
      :title="titleName"
      :visible.sync="dialogVisible"
      width="600px"
      v-dialogDrag
      @close="closeDialog"
      @opened="opened"
    >
      <el-form
        ref="goodsForm"
        :model="goodsForm"
        :rules="goodsFormRules"
        label-width="130px"
      >
        <el-form-item label="商品名称" prop="title">
          <el-input ref="input" v-model="goodsForm.title"></el-input>
        </el-form-item>
        <!-- <el-form-item label="免费价格(祭祀币)" prop="originalPrice">
          <el-input v-model="goodsForm.originalPrice" disabled></el-input>
        </el-form-item>
        <el-form-item label="收费价格(祭祀币)" prop="price">
          <el-input
            v-model.number="goodsForm.price"
            @blur="goodsForm.price = +parseInt(goodsForm.price)"
          ></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="单位" prop="unit">
          <el-input v-model="goodsForm.unit"></el-input>
        </el-form-item> -->
        <el-form-item label="商品类型" prop="categoryId">
          <el-select
            v-model="goodsForm.categoryId"
            @change="parentType"
            placeholder="请选择类型"
          >
            <el-option
              v-for="item in goodsTypeList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效时间" prop="validTime" v-if="showDay">
          <el-input
            v-model.number="goodsForm.validTime"
            @blur="goodsForm.validTime = +parseInt(goodsForm.validTime)"
            placeholder="单位:天"
          >
            <template slot="append">天</template></el-input
          >
        </el-form-item>

        <el-form-item style="height: 120px" label="上传图片">
          <div v-if="!goodsForm.imgUrl1" class="file_img img_text" @click="imgClick(1)">
            {{ imgtwo ? "上传未点亮的灯" : "上传图片" }}
          </div>
          <img class="file_img" :src="goodsForm.imgUrl1" @click="imgClick(1)" />
          <input
            class="file_input"
            type="file"
            id="file1"
            accept=".png,.jpg,.jpeg"
            @change="change"
          />

          <div
            v-if="imgtwo && !goodsForm.imgUrl2"
            class="file_img img_text file2"
            @click="imgClick(2)"
          >
            上传点亮的灯
          </div>
          <img
            v-if="imgtwo"
            class="file_img file2"
            :src="goodsForm.imgUrl2"
            @click="imgClick(2)"
          />
          <input
            class="file_input file2"
            type="file"
            id="file2"
            accept=".png,.jpg,.jpeg"
            @change="change2"
          />
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input type="textarea" v-model="goodsForm.description"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveGoods">保存</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  commodities_loadPageList,
  commodities_loadOne,
  commodities_operation,
  commodities_delete,
} from "@/api/adminConfig/goodsConfig";
import { category_loadList } from "@/api/adminConfig/goodsTypeConfig";
export default {
  name: "goodsConfig",
  data() {
    const isNumber = (rule, value, callback) => {
      if (+value >= 0) {
        callback();
      } else {
        callback(new Error("请输入正整数"));
      }
    };
    return {
      showDay: false, //天数展示与否
      loading: false,
      // typeShow: true,  // 显示是否收费
      dialogVisible: false,
      titleName: "添加商品信息",
      imgtwo: false,
      ruleForm: {
        title: "",
        categoryId: "",
      },
      pager: {
        pageSize: 20,
        total: 1,
        currentPage: 1,
      },
      tableData: [],
      goodsForm: {
        id: "",
        originalPrice: 0, //原价
        price: 0, //现价
        title: "",
        description: "",
        categoryId: "", //分类id
        // specificType: "article",
        // unit: "", //单位
        state: "1", //状态:(0:下架;1:正常销售)
        validTime: "", //有效时间 天
        imgUrl1: "",
        imgUrl2: "",
      },
      goodsTypeList: [],
      goodsFormRules: {
        title: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        categoryId: [{ required: true, message: "请选择商品类型", trigger: "change" }],
        originalPrice: [
          { validator: isNumber, trigger: "blur" },
          { validator: isNumber, trigger: "change" },
        ],
        price: [
          { required: true, message: "请输入收费价格", trigger: "blur" },
          { validator: isNumber, trigger: "blur" },
          { validator: isNumber, trigger: "change" },
        ],
        validTime: [
          { required: true, message: "请输入有效天数", trigger: "blur" },
          { validator: isNumber, trigger: "blur" },
          { validator: isNumber, trigger: "change" },
        ],
      },
    };
  },
  filters: {
    // 展示数据转换
    specificTypeChange(specificType) {
      switch (specificType) {
        case "sweep":
          return "代祭扫商品";
          break;
        case "article":
          return "供奉商品";
          break;
        case "lantern":
          return "祭祀的长明灯";
          break;
        default:
          return "";
      }
    },
  },
  mounted() {
    this.onloadGoodsList();
    this.onSubmit();
  },
  //注销window.onresize事件
  destroyed() {},
  methods: {
    async onSubmit(val) {
      if (val) {
        this.pager.currentPage = 1;
      }
      this.loading = true;
      let postData = {
        pageSize: this.pager.pageSize,
        total: this.pager.total,
        currentPage: this.pager.currentPage,
        title: this.ruleForm.title,
        categoryId: this.ruleForm.categoryId,
      };
      try {
        const res = await commodities_loadPageList(postData);
        console.log(res, 200);
        this.loading = false;
        if (res.code != 2000) {
          this.$message(res.msg ? res.msg : "数据读取失败");
          return;
        }
        this.tableData = res.data;
        // this.tableData.forEach(item => {
        //   this.goodsTypeList.forEach(item1 => {
        //     if (item.categoryId == item1.id) {
        //       item.category = item1.title;
        //     }
        //   });
        // });
        this.pager.pageSize = res.pageSize;
        this.pager.total = res.total;
        this.pager.currentPage = res.currentPage;
        //数据读取成功
      } catch (err) {
        // this.$message(err.msg);
        console.log(err, 404);
        this.$message.error(err.msg);
        this.loading = false;
        this.tableData = [];
      }
    },
    // 添加 /修改 判断第二图片是否显示
    parentType(e) {
      this.goodsTypeList.forEach((item) => {
        if (item.id == e) {
          this.showDay = item.parentId == 3;
        }
      });
      let categoryId = this.goodsForm.categoryId;
      let that = this;
      this.imgtwo = false;
      this.goodsTypeList.forEach((item) => {
        if (item.parentId == 3) {
          if (item.id == categoryId) {
            that.imgtwo = true;
            return;
          }
        }
      });
    },
    // 触发图片选择
    imgClick(i) {
      if (i == 1) {
        document.querySelector("#file1").click();
      } else {
        document.querySelector("#file2").click();
      }
    },
    // 选择图片
    change() {
      console.log(1);
      let file = document.querySelector("#file1").files[0];
      var reader = new FileReader();
      var that = this;
      console.log("base64", file);
      reader.onloadend = function () {
        //把转换后的数据给id为base64Img的src属性
        console.log(reader.result);
        that.goodsForm.imgUrl1 = reader.result;

        //这里调用了向后台发请求的代码
      };
      if (file) {
        reader.readAsDataURL(file);
      }
    },
    // 选择图片
    change2() {
      console.log(2);

      let file = document.querySelector("#file2").files[0];
      var reader = new FileReader();
      var that = this;
      console.log("base64", file);
      reader.onloadend = function () {
        //把转换后的数据给id为base64Img的src属性
        console.log(reader.result);
        that.goodsForm.imgUrl2 = reader.result;

        //这里调用了向后台发请求的代码
      };
      if (file) {
        reader.readAsDataURL(file);
      }
    },

    // // 加载自定义商品类型
    async onloadGoodsList() {
      this.loading = true;
      try {
        const res = await category_loadList({});
        console.log(res, 200);
        this.loading = false;
        if (res.code !== "2000") {
          this.loading = false;
          this.$message(res.msg ? res.msg : "数据读取失败");
          return;
        }
        this.goodsTypeList = res.data;
        // this.onSubmit();
        //数据读取成功
      } catch (err) {
        // this.$message(err);
        this.$message.error(err.msg);
        console.log(err, 404);
        this.loading = false;
        this.goodsTypeList = [];
      }
    },
    // 修改按钮点击事件 修改商品类型
    async updataGoods(id) {
      this.loading = true;
      this.titleName = "修改商品信息";
      let postData = {
        id,
      };
      console.log(postData, "postData");
      try {
        const res = await commodities_loadOne(postData);
        this.loading = false;
        console.log(res, 200);
        if (res.code !== "2000") {
          this.message.error(res.msg ? res.msg : "信息获取失败");
          return;
        }
        this.goodsForm = res.data;
        this.dialogVisible = true;
      } catch (err) {
        this.loading = false;
        this.$message.error(err.msg);
        console.log(err, 404);
      }
    },
    // 新增保存-/-保存修改
    saveGoods() {
      let that = this;
      this.$refs["goodsForm"].validate(async (valid) => {
        if (valid) {
          console.log("valid", valid);
          let postData = JSON.parse(
            JSON.stringify(this.goodsForm)
              .replace(/imgUrl1/g, "file1")
              .replace(/imgUrl2/g, "file2")
          );
          if (postData.file1) {
          } else {
            this.$message("请选择需要上传的图片");
            return;
          }
          console.log(postData, "postData");
          this.loading = true;
          try {
            const res = await commodities_operation(postData);
            console.log(res, 200);
            this.loading = false;
            if (res.code !== "2000") {
              this.$message.error(res.msg ? res.msg : "操作失败");
              return;
            }
            this.$message.success("操作成功");
            this.onSubmit();
            this.closeDialog();
          } catch (err) {
            this.loading = false;
            this.$message.error(err.msg);
            console.log(err, 404);
          }
        }
      });
    },
    opened() {
      this.$refs.input.focus();
      this.parentType();
    },
    // 关闭弹窗的回调
    closeDialog() {
      this.goodsForm = {
        id: "",
        originalPrice: 0, //原价
        price: 0, //现价
        title: "",
        description: "",
        categoryId: "", //分类id
        // specificType: "article",
        // unit: "", //单位
        state: "1", //状态:(0:下架;1:正常销售)
        validTime: "", //有效时间 天
        imgUrl1: "",
        imgUrl2: "",
      };
      document.querySelector("input[type=file]").value = "";
      this.$refs["goodsForm"].resetFields();
      this.dialogVisible = false;
      this.titleName = "添加商品信息";
    },
    //  商品配置(禁用启用)
    delGoods(id) {
      this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let postData = {
            ids: [id],
          };
          console.log(postData, "postData");
          try {
            const res = await commodities_delete(postData);
            console.log(res, 200);

            if (res.code != 2000) {
              this.$message.error(res.msg ? res.msg : "操作失败");
              return;
            }
            this.$message.success("操作成功");
            this.onSubmit();
          } catch (err) {
            console.log(err, 404);
            this.$message.error(err.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // // 显示是否收费
    // setTypeShow(data) {
    //   this.goodsTypeList.forEach(item => {
    //     if (item.id == data) {
    //       this.typeShow = item.categoryCode != "sweep";
    //     }
    //   });
    // },
    // 金额数据处理
    // moneyType(num) {
    //   let money = Math.round(num * 100) / 100;
    //   money = money.toFixed(2);
    //   return (this.goodsForm.price = money);
    // },

    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["ruleForm"].resetFields();
      this.onSubmit();
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pager.pageSize = size;
      this.onSubmit();
    },
    handleCurrentChange: function (currentPage) {
      this.pager.currentPage = currentPage;
      this.onSubmit(); //点击第几页
    },
  },
};
</script>

<style lang="scss" scoped>
.goodsConfig {
  .pageContent {
    padding: 20px;
    .form {
      height: 100%;
    }
  }
}
.fileSearch {
  .el-button {
    margin-left: 20px;
  }
}
.img_text {
  text-align: center;
  background-color: #fff;
  line-height: 100px;
  z-index: 1;
  border: 1px solid #f0f0f0;
}
.file_img {
  position: absolute;
  top: 9px;
  width: 100px;
  height: 100px;
  cursor: pointer;
}
.file_input {
  color: #ffffff00;
  display: none;
  width: 100px;
  height: 100px;
}
.file2 {
  margin-left: 120px;
}
.el-image {
  width: 70px;
  height: 70px;
  margin: 0 5px 0;
}
</style>
